/*
 * @Description:
 * @Autor: dongjunhua
 * @Date: 2021-01-15 13:34:15
 * @LastEditors: dongjunhua
 * @LastEditTime: 2021-10-17 14:22:16
 */
import axios from 'axios';
import store from '@/store';
import { ElNotification } from 'element-plus';

const axiosInstance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60000
});

axiosInstance.interceptors.request.use(
  config => {
    store.dispatch('app/startLoading');
    return config;
  },
  error => {
    store.dispatch('app/endLoading');
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  response => {
    store.dispatch('app/endLoading');
    return response.data;
  },
  error => {
    store.dispatch('app/endLoading');
    // console.log(error.response);
    ElNotification({
      message: error.response.statusText,
      type: 'error',
      duration: 5 * 1000
    });
    if (error.response.status === 401) {
      // set beforeLogout option as empty function so Relam.beforeLogout will not execute
      store.dispatch('subject/logout', { beforeLogout: () => {} });
    }
  }
);

export default axiosInstance;
